#include "SqlDef.h"
#include "DaoAttach.h"

using namespace attachInfo;

DaoAttach::DaoAttach()
{

}

//add by san
int DaoAttach::getAttachList(const chapterInfo::ChapterInfo& chapter,  attachInfo::AttachInfo* attachList)
{
  static char sql[SQL_LENGTH];
  sprintf(sql, SQL_ATTACH_SELECT_LIST, chapter.articleid.c_str(),chapter.chapterid.c_str());
  TRAVERSE_AND_RETURN_ROWS(attachList);
}

int DaoAttach::traverseResult(const MYSQL_RES *res, attachInfo::AttachInfo* attachList)
{
  static MYSQL_ROW row;
  int count= 0;
  while ((row = mysql_fetch_row(const_cast<MYSQL_RES*>(res))) != NULL)
  {
    fillAttach(row, attachList[count]);
    ++count;
  }
  return count;
}

  void DaoAttach::fillAttach(const MYSQL_ROW& row, attachInfo::AttachInfo& attach)
  {
      attach.articleid.assign(row[attach_attachid]);
      attach.articleid.assign(row[attach_articleid]);
      attach.chapterid.assign(row[attach_chapterid]);
      attach.cname.assign(row[attach_name]);
      attach.cclass.assign(row[attach_class]);
      attach.postfix.assign(row[attach_postfix]);
      attach.csize.assign(row[attach_size]);
      attach.hits.assign(row[attach_hits]);
      attach.needexp.assign(row[attach_needexp]);
      attach.uptime.assign(row[attach_uptime]);
  }

void DaoAttach::addAttach(const attachInfo::AttachInfo& attach)
{
    static char sql[SQL_LENGTH];
    sprintf(sql, SQL_ATTACH_INSERT,
            attach.attachid.c_str(), attach.articleid.c_str(),attach.chapterid.c_str(),
            attach.cname.c_str(),attach.cclass.c_str(),attach.postfix.c_str(),
            attach.csize.c_str(),attach.hits.c_str(),attach.needexp.c_str(),
            attach.uptime.c_str(),attach.isactive.c_str());
    doDml(sql);
}

void DaoAttach::updateAttachInvalid(const std::string& articleid)
{
  static char sql[SQL_LENGTH];
  sprintf(sql, SQL_ATTACH_UPDATE_INVALID, articleid.c_str());
  doDml(sql);
}

void DaoAttach::getAttachMaxID(std::string &buffer)
{
  buffer = "";
  MYSQL_RES* res = doQuery(SQL_ATTACH_MAXID);
  static MYSQL_ROW row;
  static char tmp[12];
  while((row = mysql_fetch_row(res)) != NULL)
  {
    if(row[0] != NULL && strlen(row[0]) > 0)
    {
      sprintf(tmp,"%d",atoi(row[0]) + 1);
      buffer.assign(tmp);
    }
  }
  if (buffer.empty() == true) { buffer = "1"; }
  mysql_free_result(res);
}
